package com.xbn.xbnmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xbn.common.constant.ProductConstant;
import com.xbn.common.to.SkuHasStockVo;
import com.xbn.common.to.SkuReductionTo;
import com.xbn.common.to.SpuBoundsTo;
import com.xbn.common.to.es.SkuEsModel;
import com.xbn.common.utils.R;
import com.xbn.xbnmall.product.dao.SpuInfoDescDao;
import com.xbn.xbnmall.product.entity.*;
import com.xbn.xbnmall.product.feign.CouponFeignService;
import com.xbn.xbnmall.product.feign.SearchFeignService;
import com.xbn.xbnmall.product.feign.WareFeginService;
import com.xbn.xbnmall.product.service.*;
import com.xbn.xbnmall.product.vo.addProductVo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbn.common.utils.PageUtils;
import com.xbn.common.utils.Query;

import com.xbn.xbnmall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeginService wareFeginService;
    @Autowired
    private SearchFeignService searchFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @GlobalTransactional
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
     //1、保存基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //拷贝vo中的基础信息，但是要注意缺少一个create_time和update_time,需要自己设置
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(vo,spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        //2、保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        //所有描述图片地址信息使用  ， 分割
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        //4、保存spu的规格参数 ； pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValues  = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
            productAttrValueService.saveBatch(attrValues);


        //5、保存spu的积分信息  跨库 xbnmall_sms库中的 sms_spu_bounds表
        //对优惠券微服务进行访问。
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r1.getCode()!=0)
        {
            log.error("远程保存spu积分信息失败");
        }
        //6、保存当前spu对应的所有的sku信息
        List<Skus> skus = vo.getSkus();
        if(skus!=null&&skus.size()>0)
        skus.forEach(sku->{

            //查找默认图片
            String defaultImg="";
            for (Images img : sku.getImages()) {
                if(img.getDefaultImg()==1)
                {
                    defaultImg=img.getImgUrl();
                }
            }
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku,skuInfoEntity);
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSkuDefaultImg(defaultImg);
            //6.1   sku基本信息的保存 pms_sku_info
            skuInfoService.save(skuInfoEntity);

            //6.2    sku的图片信息   pms_sku_images
            Long skuId = skuInfoEntity.getSkuId();
            List<SkuImagesEntity> imgs = sku.getImages().stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setDefaultImg(img.getDefaultImg());

                return skuImagesEntity;
            }).filter(img1->{
                //过滤掉没有被选中的图片，也就是没有路径的
                return !StringUtils.isEmpty(img1.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(imgs);


            //6.3  sku的销售属性信息   pms_sku_sale_attr_value
            List<Attr> saleAttrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> saleAttrEntities = saleAttrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(saleAttrEntities);


   /*     6.4   sku的优惠、满减等信息 跨库，操作xbnmall_sms数据库中的折扣表sms_sku_ladder
        以及满减表sms_sku_full_reduction还有会员价格表sms_member_price
        */

            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sku,skuReductionTo);
            skuReductionTo.setSkuId(skuId);
            if(skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(new
                    BigDecimal("0"))==1)
            {
                R r = couponFeignService.saveSkuReduction(skuReductionTo);
                if(r.getCode()!=0)
                {
                    log.error("远程保存spu优惠信息失败");
                }
            }


        });







    }

    /*
    *
    * */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key))
        {
            wrapper.and(wrapper1->{
                wrapper1.eq("id",key).or().like("spu_name",key).or().
                        like("spu_description",key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status))
        {
           wrapper.eq("publish_status",status);

        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId))
        {
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId))
        {
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),wrapper

        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //查询处当前spuid对应的所有的sku的信息
        List<SkuInfoEntity> skus=  skuInfoService.getSkusBySpuId(spuId);
      /*
         查询当前sku所有可以被检索的的规格属性，由于规格属性是按照spu来查询的
        所以循环外面查询一遍然后统计设置就好了
        */
        List<ProductAttrValueEntity> attrValueEntityList = productAttrValueService.baseAttrListForSpu(
                spuId
        );
        //然后看那些属性是可以被检索的
        List<SkuEsModel.Attrs> attrsList=new ArrayList<>();
        List<Long> attrIds = attrValueEntityList.stream().map(attrVal -> {
            return attrVal.getAttrId();
        }).collect(Collectors.toList());
        if(attrIds!=null&&attrIds.size()>0) {
            List<Long> searchAttrsIds = attrService.selectSearchAttrs(attrIds);
            Set<Long> idSet =new HashSet<>(searchAttrsIds);
            attrsList = attrValueEntityList.stream().filter(attr -> {
                return idSet.contains(attr.getAttrId());
            }).map(item -> {
                SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                BeanUtils.copyProperties(item, attrs);
                return attrs;
            }).collect(Collectors.toList());

        }


        //查询库存
        // 发送远程调用库存系统去查询库存ware（只查询是否有库存）
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> skuWareMap=new HashMap<>();
        try {
            R skusHasStock = wareFeginService.getSkusHasStock(skuIds);
      List<SkuHasStockVo> dataJsonTrans=skusHasStock.getData(
                    new TypeReference<List<SkuHasStockVo>>(){}
                    );
           skuWareMap = dataJsonTrans.stream().collect(Collectors.toMap(item->item.getSkuId(),
                   item -> item.getHasStock()
           ));
       }catch (Exception e)
       {
           log.error("库存服务异常：{}",e);
       }
        //封装sku信息准备给es
        Map<Long, Boolean> finalSkuWareMap = skuWareMap;
        List<SkuEsModel.Attrs> finalAttrsList = attrsList;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            //相同属性对拷
            BeanUtils.copyProperties(sku,skuEsModel);
            //还需要处理的属性skuPrice,skuImg,hasStock,hotScore
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //库存
            if(finalSkuWareMap ==null) {
                skuEsModel.setHasStock(true);
            }
            else {
                skuEsModel.setHasStock(finalSkuWareMap.get(skuEsModel.getSkuId()));
            }
            //TODO 热度评分，先默认0
            skuEsModel.setHotScore(0L);
            //查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(finalAttrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        // 发给远程es进行保存
        R r = searchFeignService.productStatusUp(upProducts);
        if(r.getCode()==0)
        {
            //远程调用成功改变当前是上架的商品的spu的状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }
        else {
            //远程调用失败
        }
    }

    @Override
    public SpuInfoEntity getSpuBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId=byId.getSpuId();
        SpuInfoEntity byId1 = getById(spuId);

        return byId1;
    }


}